import useFetch from "@/lib/hooks/useFetch";
import FullSizeModal from "../FullSizeModal";
import { getDeviceProgram } from "@/lib/api/device";
import { useAtomValue } from "jotai";
import { tokenAtom } from "@/store/user";
import ProgramStatus from "../ProgramList/ProgramStatus";
import { Button, Form, Input, InputNumber } from "antd";
import { jumpStep } from "@/lib/api/deviceStatus";
import { useMessage } from "@/providers/AntdMessageProvider";
import getRequestErrorMessage from "@/lib/utils/getRequestErrorMessage";
import { useState } from "react";
import useOnUpdated from "@/lib/hooks/useOnUpdated";

type JumpStepDialogProps = {
  deviceId: number;
  visible: boolean;
  onClose: () => void;
  onSuccess: () => void;
};

export default function JumpStepDialog(props: JumpStepDialogProps) {
  const { deviceId, visible, onClose, onSuccess } = props;
  const [formData, setFormData] = useState<{
    loop?: number;
    segmentLoop?: number;
    segmentNo?: number;
    stepNo?: number;
  }>({
    loop: 1,
    segmentLoop: 1,
    segmentNo: undefined,
    stepNo: undefined,
  });
  const token = useAtomValue(tokenAtom);
  const message = useMessage();
  const {
    isLoading,
    isPending,
    data,
    refetch: loadDeviceProgram,
  } = useFetch({
    fetchFn: () =>
      getDeviceProgram(deviceId, token).then((res) => {
        if (res.code !== 200) {
          throw res;
        }
        return res.data.programData;
      }),
  });

  const { isLoading: isJumpStepLoading, refetch: handleJumpStep } = useFetch({
    fetchFn: (data: Required<typeof formData>) =>
      jumpStep({ deviceId, ...data }, token).then((res) => {
        if (res.code !== 200) {
          throw res;
        }
      }),
    onError(error) {
      message.error(getRequestErrorMessage(error, "操作失败！"));
    },
    onSuccess() {
      onSuccess();
      onClose();
      message.success("操作成功");
    },
  });

  useOnUpdated(() => {
    visible && loadDeviceProgram();
  }, [visible]);

  function handleSubmit() {
    for (const k in formData) {
      if (formData[k as keyof typeof formData] === undefined) {
        message.error("缺少必须参数！");
        return;
      }
    }
    handleJumpStep(formData as Required<typeof formData>);
  }

  return (
    <FullSizeModal visible={visible} onClose={onClose} title="跳步" fullscreen>
      <div className="h-full overflow-auto px-10 pt-6">
        <ProgramStatus
          data={data || []}
          loading={isPending || isLoading}
          selectable={["step"]}
          onSelectionChange={(data) => {
            setFormData((p) => ({
              ...p,
              segmentNo: data ? data.records[0].segmentNo : undefined,
              stepNo: data ? data.records[0].stepNo : undefined,
            }));
          }}
        />
        <Form layout="inline" className="p-6">
          <Form.Item label="程序循环">
            <InputNumber
              value={formData.loop}
              onChange={(v) =>
                setFormData((p) => ({ ...p, loop: v || undefined }))
              }
            />
          </Form.Item>
          <Form.Item label="段循环">
            <InputNumber
              value={formData.segmentLoop}
              onChange={(v) =>
                setFormData((p) => ({ ...p, segmentLoop: v || undefined }))
              }
            />
          </Form.Item>
          <Form.Item>
            <Button
              type="primary"
              loading={isJumpStepLoading}
              onClick={handleSubmit}
            >
              确定
            </Button>
          </Form.Item>
        </Form>
      </div>
    </FullSizeModal>
  );
}
